package controllers

import (
	"encoding/json"
	"genealogy/models"
	"genealogy/pkg/app"
	"genealogy/pkg/e"
	"genealogy/services"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetGenealogy(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchNo := ""
	if arg := c.Query("searchName"); arg != "" {
		searchNo = arg
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
		"searchNo": searchNo,
	}
	err, info, total := services.GetAllGenealogy(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

func DelGenealogy(c *gin.Context) {
	id := ""
	if arg := c.Query("genealogy_no"); arg != "" {
		id = arg
	}
	if id == "" {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelGenealogy(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

func UpdateGenealogy(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["GenealogyNo"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	GenealogyNo := m["GenealogyNo"]
	GenealogyName := m["GenealogyName"]
	err := services.UpdateGenealogy(models.Genealogy{GenealogyNo: GenealogyNo, GenealogyName: GenealogyName, Isdel: false, UpdateTime: time.Now()})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

func AddGenealogy(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	GenealogyNo := m["GenealogyNo"]
	GenealogyName := m["GenealogyName"]
	err := services.AddGenealogy(models.Genealogy{GenealogyNo: GenealogyNo, GenealogyName: GenealogyName, Isdel: false, UpdateTime: time.Now()})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}
